package com.chen106106.sstest.action;

import java.util.Arrays;
import net.sf.json.JSONArray;

import com.chen106106.sstest.common.JSONUtils;
import com.chen106106.sstest.common.PageHolder;
import com.chen106106.sstest.model.Article;
import com.chen106106.sstest.service.ArticleMgrService;
import com.opensymphony.xwork2.ActionSupport;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

public class ArticleMgrAction extends ActionSupport{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 4209181271110126570L;

	private ArticleMgrService articleMgrService;
	
	private Logger log = Logger.getLogger(ArticleMgrAction.class);
	
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	
	private int articleId;
	private String title;
	private String content;
	private String source;
	private String releaseDate;
	private PageHolder<Article> pageHolder = new PageHolder<Article>(10);
	
	
	//不写type的时候，默认就是dispatcher的方式，主要这里如果前台是通过ajax方式发送请求的，那么后台的type应该设置成dispatcher方式，否则数据返回不了。
		@Action(value="article-list",results={@Result(name=SUCCESS,location="/article/list.jsp")})
		public String articleList(){
			
//			int beginIndex = 1;
//			int num = 30;
//			int[]params = new int[]{beginIndex,num};
			
			
//			pHolder.setPageIndex();//当前页的页码
//			pHolder.setPageSize();//每页的大小
	//
//			pHolder.setRowCount(dao.count(...));//获取数据库里的总记录数
//			pHolder.setList(dao.list(...));//从数据库获取当前页的数据
			
			int rowCount = articleMgrService.getArticleCount();
			pageHolder.setRowCount(rowCount);
			
			int pageSize = pageHolder.getPageSize();
			int offSet = pageHolder.getRowOffset();
			List<Article>articles = articleMgrService.queryList(offSet, pageSize);
			request.setAttribute("articleList", articles);
			pageHolder.setList(articles);
			String result = request.getParameter("result");
			if(!StringUtils.isEmpty(result)){
				int id = Integer.parseInt(result);
				if(id>0){
					request.setAttribute("result", result);
				}
			}
			return SUCCESS;
			
		}

		
	/**
	 * 显示添加页面
	 * @return
	 */
	@Action(value="show-add-article",results={@Result(name=SUCCESS,location="/article/add-article.jsp")})
	public String showAdd(){
		
		return SUCCESS;
		
	}
	/**
	 * 处理添加请求
	 * @return
	 */
	@Action(value="add-article",results = {@Result(name = SUCCESS, type = "redirect", location = "/article/index.jsp")})
	public String addArticle(){
		
		
		Article article = new Article();
		try {
		if(!StringUtils.isEmpty(title)){
			title = URLDecoder.decode(title, "utf-8");
		}
		if(!StringUtils.isEmpty(content)){
			content = URLDecoder.decode(content, "utf-8");
		}
		if(!StringUtils.isEmpty(source)){
			source = URLDecoder.decode(content, "utf-8");
		}
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		article.setTitle(title);
		content = htmlspecialchars(content);
		article.setContent(content);
		article.setReleaseDate(getReleaseDate(releaseDate));
		article.setSource(source);
		long result = articleMgrService.addArticle(article);
//		request.setAttribute("result", result);
		
//		try {
//			response.sendRedirect("article-list.do?result="+result);
//		} catch (IOException e) {
//			log.error(e.getMessage(),e);
//		}
//		Map<String,Object> jsonMap = new HashMap<String,Object>();
//		jsonMap.put("result", result);
//		String json = JSONObject.fromObject(jsonMap).toString();
//		JSONUtils.ajaxWrite(response, json);
		
		return SUCCESS;
	}
	
	/**
	 * 显示更新页面
	 * @return
	 */
	@Action(value="show-update-article",results={@Result(name=SUCCESS,location="/article/update-article.jsp")})
	public String showUpdate(){
		
		Article article = null;
		try{
			if(0!=articleId){
				article = articleMgrService.queryArticleById(articleId);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		request.setAttribute("article", article);
		return SUCCESS;
		
	}
	
	/**
	 * 处理更新文章的请求
	 * @return
	 */
	@Action(value="update-article",results = {@Result(name = SUCCESS, type = "redirect", location = "article-list.do")})
	public String updateUser(){
		boolean result = false;
		try{
			if(0!=articleId){
				try {
					if (!StringUtils.isEmpty(title)) {
						title = URLDecoder.decode(title, "utf-8");
					}
					if (!StringUtils.isEmpty(content)) {
						content = URLDecoder.decode(content, "utf-8");
					}
					if (!StringUtils.isEmpty(source)) {
						source = URLDecoder.decode(source, "utf-8");
					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
				Article article = new Article();
				article.setId(articleId);
				article.setTitle(title);
				article.setContent(content);
				article.setReleaseDate(getReleaseDate(releaseDate));
				article.setSource(source);
				result = articleMgrService.updateArticle(article);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
//		Map<String,Object> jsonResult = new HashMap<String, Object>();
//		jsonResult.put("result", result);
//		String json = JSONObject.fromObject(jsonResult).toString();
//		JSONUtils.ajaxWrite(response, json);
		return SUCCESS;
	}
	
	@Action(value = "preview-content")
	public String preview_content() {
		Article article = null;
		int articleId = Integer.valueOf(request.getParameter("id"));
		try {
			if (0 != articleId) {
				article = articleMgrService.queryArticleById(articleId);
				String[] arry = article.getContent()
						.replaceAll("  ", "")
						// .replaceAll("\\s*", "")
						.split("<hr style=\"page-break-after:always;\" class=\"ke-pagebreak\" />");

				List list = Arrays.asList(arry);
				// StringBuilder s = new StringBuilder();
				// s.append("{");
				// for (int i = 0; i < arry.length; i++) {
				// s.append("{\"").append(i).append("\":\"").append(arry[i])
				// .append("\"},");
				// }
				// if (s.length() > 1) {
				// s.delete(s.length() - 1, s.length());
				// }
				// s.append("}");
				// Map<String, Object> jsonResult = new HashMap<String,
				// Object>();
				// jsonResult.put("result", arry);
				// String json = JSONObject.fromObject(jsonResult).toString();
				// JSONUtils.ajaxWrite(response, s.toString());

				// Map<String,Object> jsonResult = new HashMap<String,
				// Object>();
				// jsonResult.put("result", article);
				JSONArray json = new JSONArray();
				JSONArray jsonArray = json.fromObject(list);
				// String json = JSONObject.fromObject(list).toString();
				JSONUtils.ajaxWrite(response, jsonArray.toString());
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
	@Action(value = "article-preview", results = {@Result(name = SUCCESS, location = "/article/preview.jsp")})
	public String preview() {
		Article article = null;
		int articleId = Integer.valueOf(request.getParameter("id"));
		try {
			if (0 != articleId) {
				article = articleMgrService.queryArticleById(articleId);
				String[] arry = article
						.getContent()
						.split("<hr style=\"page-break-after:always;\" class=\"ke-pagebreak\" />");
				request.setAttribute("article_content_count", arry.length);
				request.setAttribute("article", article);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return null;
		}
		return SUCCESS;
	}


	
	@Action(value="get-article-info",results={@Result(name=SUCCESS,type="redirect",location="/article/update-user.jsp")})
	public String getArticleInfo(){
		Article article = null;
		try{
			if(0!=articleId){
				article = articleMgrService.queryArticleById(articleId);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
//		Map<String,Object> jsonResult = new HashMap<String, Object>();
//		jsonResult.put("article", article);
//		String json = JSONObject.fromObject(jsonResult).toString();
//		JSONUtils.ajaxWrite(response, json);
		return SUCCESS;
	}
	
	@Action(value="delete-article",results = {@Result(name = SUCCESS, type = "redirect", location = "/article/index.jsp")})
	public String deleteUser(){
		boolean result = false;
		try{
			if(0!=articleId){
			
				result = articleMgrService.deleteArticle(articleId);
			}
			
		}catch(Exception e){
			log.error(e.getMessage(),e);
		}
		Map<String,Object> jsonResult = new HashMap<String, Object>();
		jsonResult.put("result", result);
		String json = JSONObject.fromObject(jsonResult).toString();
		JSONUtils.ajaxWrite(response, json);
		return NONE;
	}
	
	/**
	 * 上传图片
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "user-upload", results = {
			@Result(name = SUCCESS, location = "/article/index.jsp")})
	public String uploadImage() {
		/*	
		try {

			String errorMessage[] = new String[1];
				String url = request.getParameter("photo1");
				String fileName = "";
				//String title = request.getParameter("title");
				if(!StringUtils.isEmpty(url)){
					 fileName = modulePhotoStorage.save("anlian",
							PhotoUtils.getImage(url));
					 
				}else{
					byte[] photoBytes = PhotoUtils.checkFile(photo, errorMessage);
					if (errorMessage[0] != null) {
						request.setAttribute("errorMeg", errorMessage[0]);
						return ERROR;
					}

					fileName = modulePhotoStorage.save("anlian",photoBytes);
				}

				String imageUrl = ElFunctions.getModulePhotoUrl("anlian", fileName, 0);
				request.setAttribute("phoneName", fileName);
				request.setAttribute("image_url",imageUrl);
				log.info(imageUrl);
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			*/
			return SUCCESS;
	}
	/**
	 * 根据字符串格式的日期获取date类型的日期
	 * @param releaseDate
	 * @return
	 */
	public Date getReleaseDate(String releaseDate){
		
		if(StringUtils.isEmpty(releaseDate)){
			return null;
		}
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(releaseDate);
			return date;
		}catch(Exception e){
			log.error(e.getMessage(),e);
			return null;
		}
	}
	/**
	 * 对html中的特殊字符进行转译
	 * @param str
	 * @return
	 */
	private String htmlspecialchars(String str) {
		if(StringUtils.isEmpty(str)){
			return "";
		}
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}
	public void setArticleMgrService(ArticleMgrService articleMgrService) {
		this.articleMgrService = articleMgrService;
	}


	public void setArticleId(int articleId) {
		this.articleId = articleId;
	}


	public void setTitle(String title) {
		this.title = title;
	}


	public void setContent(String content) {
		this.content = content;
	}


	public void setSource(String source) {
		this.source = source;
	}


	public void setReleaseDate(String releaseDate) {
		this.releaseDate = releaseDate;
	}


	public void setPageHolder(PageHolder<Article> pageHolder) {
		this.pageHolder = pageHolder;
	}


	public PageHolder<Article> getPageHolder() {
		return pageHolder;
	}
	
	
}
